package com.wonders.ssm.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * 验证码
 * Created by lv on 2018/8/6.
 */
@Component("imageCode")
public class ImageCode {

    @Value("${image.width}")
    private int width;

    @Value("${image.height}")
    private int height;

    @Value("${image.codeLength}")
    private int codeLength;

    @Value("${image.randomString}")
    private String randomString;

    @Value("${image.font.name}")
    private String fontName;

    @Value("${image.font.style}")
    private int fontStyle;

    @Value("${image.font.size}")
    private int fontSize;

    @Value("${image.sessionKeyCode}")
    private String sessionKeyCode;

    public BufferedImage getImage(HttpServletRequest request){
        //定义画布
        BufferedImage image =  new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        //得到画笔
        Graphics g = image.getGraphics();
        //生成随机类
        Random random = new Random();
        //getRandColor(100,250)

        //设置颜色,画边框
        g.setColor(new Color(240,243,250));
        g.fillRect(0,0,width,height);


        //设置字体颜色
        g.setColor(Color.blue);
        g.setFont(new Font(fontName,fontStyle,fontSize));

        //随机验证码
        String sRand = randomRand(codeLength);
        int strWidth = width / 2 - g.getFontMetrics().stringWidth(sRand) / codeLength - fontSize;
        int strHeight = height / 2 + g.getFontMetrics().getHeight() / 4;
        for (int i = 0; i < codeLength; i++) {
            String rand = sRand.substring(i, i + 1);
            g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
            g.drawString(rand, 13 * i + strWidth, strHeight);
        }
        //干扰线
        for (int i = 0; i < codeLength; i++) {
            g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
            g.drawLine(10+random.nextInt(60), 5+random.nextInt(30), 10+random.nextInt(60), 5+random.nextInt(30));
        }
        HttpSession session = request.getSession();

        session.setAttribute("sessionKeyCode", sRand);
        //System.out.println(session.getId());
        //request.setAttribute("sRand", sRand);
        g.dispose();
        return image;
    }

    private String randomRand(int n) {
        String rand = "";
        int len = randomString.length() - 1;
        double r;
        for (int i = 0; i < n; i++) {
            r = ((Math.random())) * len;
            rand = rand + randomString.charAt((int) r);
        }
        return rand;
    }


}
